/**
 * 中国9号健康产业有限公司
 * Copyright (C) JiuHaoHealth Corporation. All Rights Reserved
 */
package com.jiuhaohealth.common.datasource;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * @author minghui(jackchenmh@gmail.com)
 * @version 2014-3-18 下午5:08:45
 */
public class MultiDataSource implements DataSource {  
		static Logger logger = LoggerFactory.getLogger(MultiDataSource.class);  
	   
	   private Map<String , DataSource> mappedDataSources;  

	   private DataSource defaultDataSource;

	   public MultiDataSource(){  
	       mappedDataSources = new HashMap<String , DataSource>(4);  
	   }  
	     
	   /** 
	    * 数据库连接池初始化 
	    * 该方法通常在web 应用启动时调用 
	    */  
	   public void initialMultiDataSource(){  
	       Collection<DataSource> dsCollection = mappedDataSources.values();  
	       for(DataSource ds : dsCollection){  
	           if(ds != null){  
	               Connection conn = null;  
	               try {  
	                   conn = ds.getConnection();  
	               } catch (SQLException e) {  
	                   e.printStackTrace();  
	               } finally{  
	                   if(conn != null){  
	                       try {  
	                           conn.close();  
	                       } catch (SQLException e) {  
	                           e.printStackTrace();  
	                       }  
	                       conn = null;  
	                   }  
	               }  
	           }  
	       }  
	   }  

	   
	   /** 
	    * 获取当前线程绑定的DataSource 
	    * @return 
	    */  
	   public DataSource getCurrentDataSource() {  
		   String key = getDataSourceKey();
		   if(key != null){
			   return mappedDataSources.get(key);
		   } else {
			   return defaultDataSource;
		   }
	    }  
	  
	    public Map<String, DataSource> getMappedDataSources() {  
	        return mappedDataSources;  
	    }  
	  
	    public void setMappedDataSources(Map<String, DataSource> mappedDataSources) {  
	        this.mappedDataSources = mappedDataSources;  
	    }  
	    
	    public void setDefaultDataSource(DataSource defaultDataSource) {
			this.defaultDataSource = defaultDataSource;
		}

		   
	    /** 
	     * 使用Key选择当前的数据源 
	     * @param key 
	     */  
	    public void choiceMappedDataSources(String key){  
	        DataSource ds = this.mappedDataSources.get(key);  
	        if(ds == null){  
	            throw new IllegalStateException("No Mapped DataSources Exist!");  
	        }  
	        //this.currentDataSourceHolder.set(ds);  
	    }
	  

	    public Connection getConnection() throws SQLException {  
	        if(getCurrentDataSource() != null){  
	            return getCurrentDataSource().getConnection();  
	        }  
	        return null;  
	    }  
	  

	    public Connection getConnection(String username, String password)  
	            throws SQLException {  
	        if(getCurrentDataSource() != null){  
	            return getCurrentDataSource().getConnection(username , password);  
	        }  
	        return null;  
	    }  

	    public PrintWriter getLogWriter() throws SQLException {  
	        if(getCurrentDataSource() != null){  
	            return getCurrentDataSource().getLogWriter();  
	        }  
	        return null;  
	    }  
	  
	    public int getLoginTimeout() throws SQLException {  
	        if(getCurrentDataSource() != null){  
	            return getCurrentDataSource().getLoginTimeout();  
	        }  
	        return 0;  
	    }  
	   
	    public void setLogWriter(PrintWriter out) throws SQLException {  
	        if(getCurrentDataSource() != null){  
	            getCurrentDataSource().setLogWriter(out);  
	        }  
	    }  
	  
	    public void setLoginTimeout(int seconds) throws SQLException {  
	        if(getCurrentDataSource() != null){  
	            getCurrentDataSource().setLoginTimeout(seconds);  
	        }  
	    }  
	  
	    public boolean isWrapperFor(Class<?> iface) throws SQLException {  

	        return false;  
	    }  
	  

	    public <T> T unwrap(Class<T> iface) throws SQLException {  

	        return null;  
	    }  
	    
		 private final static ThreadLocal<String> dataSourceKeyHolder = new ThreadLocal<String>();

		 public static void chooseDateSource(DataSourceChooser chooser){
			   dataSourceKeyHolder.set(chooser.choose());
		 }
		 
		 public static void setDataSourceKey(String key){
			   dataSourceKeyHolder.set(key);
		 }
		   
		 public static String getDataSourceKey(){
			   return dataSourceKeyHolder.get();
		 }
		 
		 public static void removeDataSourceKey(){
			   dataSourceKeyHolder.remove();
		 }

		public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException {
			return null;
		}
}